
//
//  TBHomeVCViewModel.swift
//  新浪微博
//
//  Created by bin on 16/2/3.
//  Copyright © 2016年 XMG. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class TBHomeVCViewModel: NSObject {
    var isLoadMore = false
    var text = "0"
    lazy var status:[TBStatusViewModel] = [TBStatusViewModel]()
    var block: ((count: String) -> Void)?
    func loadData(){
        //3.发送网络请求
        var since_id =  status.first?.status.idstr ?? "0"
        let max_id =  status.last?.status.idstr ?? "0"
        var maxID = "\(Int(max_id)! - 1)"
        if isLoadMore{
            since_id = "0"
            isLoadMore = false
        }else{
            maxID = "0"
        }
        TBNetWorkTools.shareInstance.getStatus (since_id, max_id: maxID){(dicts, error) -> Void in
            if nil != error{
                print("\(error)")
                SVProgressHUD.showErrorWithStatus("请求出错")
                return
            }
            guard let dictArr = dicts else
            {   print("微博字典nil")
                SVProgressHUD.showErrorWithStatus("请求出错")
                return
            }
            var modelArr = [TBStatusViewModel]()
            
            for dict in dictArr{
                
                modelArr.append(TBStatusViewModel(status: TBStatus(dict: dict)))
            }
            
            //“0” 第一次全新加载
            if since_id == "0" && maxID == "0"{
                self.status = modelArr
                self.text = "加载新数据"
            }else if since_id != "0" {
                self.status = modelArr + self.status
                self.text = "加载\(modelArr.count)条数据"
            }else{
                self.status = self.status + modelArr
                self.text = "上拉加载\(modelArr.count)条数据"
            }
            
            //4.缓存图片
            self.loadPic(self.status)
            
        }

    }
    
    
    
    private func loadPic(statusArr: [TBStatusViewModel]){
        
        let group = dispatch_group_create()
        
        for status in statusArr{
            
            for url in status.imageURLs!{
                
                dispatch_group_enter(group)
                
                let urlStr = url.absoluteString
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlStr), options: SDWebImageOptions(rawValue: 0), progress: nil, completed: {(_, error, _, _, _) -> Void in
                    //                TBLog("a done")
                    dispatch_group_leave(group)
                })
                
            }//一条微博的图片
            
        }//所有微博
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //            TBLog("all hava done")
            self.block!(count: self.text)
            
        }
    }

}
